package com.linb.pan.server.common.stream.consumer.search;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.linb.pan.core.utils.IdUtil;
import com.linb.pan.server.common.stream.channel.PanChannels;
import com.linb.pan.server.common.stream.event.search.FileSearchEvent;
import com.linb.pan.server.modules.user.entity.BPanUserSearchHistory;
import com.linb.pan.server.modules.user.service.IUserSearchHistoryService;
import com.linb.pan.stream.core.AbstractConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.context.event.EventListener;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.messaging.Message;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class FileSearchEventListener extends AbstractConsumer {

    @Autowired
    private IUserSearchHistoryService searchHistoryService;

    /**
     * 监听文件搜索
     */
    @StreamListener(PanChannels.USER_SEARCH_INPUT)
    @Async(value = "eventListenerTaskExecutor")
    public void saveSearchHistory(Message<FileSearchEvent> message) {
        if (isEmptyMessage(message)) {
            return;
        }
        printLog(message);
        FileSearchEvent event = message.getPayload();

        BPanUserSearchHistory history = new BPanUserSearchHistory();
        history.setId(IdUtil.get());
        history.setUserId(event.getUserId());
        history.setSearchContent(event.getKeyword());
        history.setCreateTime(new Date());
        history.setUpdateTime(new Date());
        try {
            //保存操作
            searchHistoryService.save(history);
        } catch (DuplicateKeyException e) {
            //更新操作
            UpdateWrapper updateWrapper = Wrappers.update();
            updateWrapper.eq("user_id", event.getUserId());
            updateWrapper.eq("search_content", event.getKeyword());
            updateWrapper.set("update_time", new Date());
            searchHistoryService.update(updateWrapper);
        }
    }

}
